import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import '../service/service_method.dart';
import '../subpages/home_sub/swiperdiy.dart';
import '../subpages/home_sub/topnavigator.dart';
import '../subpages/home_sub/adbanner.dart';
import '../subpages/home_sub/leaderphone.dart';
import '../subpages/home_sub/Recommend.dart';
import '../subpages/home_sub/floor.dart';
import '../subpages/home_sub/advertisement.dart';
import 'dart:convert';
import 'package:flutter_shop/routers/application.dart';//引入路由文件


class HomePage extends StatefulWidget {
  _HomePageState createState() => _HomePageState();
}

//AutomaticKeepAliveClientMixin 页面保持
class _HomePageState extends State<HomePage>
    with AutomaticKeepAliveClientMixin {
  @override
// TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
  int page = 1;
  List<Map> hotGoodsList = [];
  //刷新插件要求的
  GlobalKey<RefreshFooterState> _footerKey =
      new GlobalKey<RefreshFooterState>();
  GlobalKey<RefreshHeaderState> _headerKey =
      new GlobalKey<RefreshHeaderState>();
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    print('加载');
  }

  @override
  Widget build(BuildContext context) {
    var formData = {'lon': '117.02932', 'lat': '36.76189'};

    return Scaffold(
        appBar: AppBar(
          title: Text('百姓生活+'),
        ),
        body: FutureBuilder(
          // future: getHomePageContent(),//调用接口
          future: request('homePageContext', formData: formData), //调用接口
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              //数据处理
              var data = json.decode(snapshot.data.toString());
              List<Map> swiperDataList =
                  (data['data']['slides'] as List).cast(); // 顶部轮播组件数
              List<Map> navigatorDataList =
                  (data['data']['category'] as List).cast(); // 顶部导航栏数据
              String adPicture =
                  data['data']['advertesPicture']['PICTURE_ADDRESS']; //广告图片
              String leaderImage = data['data']['shopInfo']['leaderImage'];
              String leaderPhone = data['data']['shopInfo']['leaderPhone'];
              List<Map> recommendList =
                  (data['data']['recommend'] as List).cast();
              String floor1Title =
                  data['data']['floor1Pic']['PICTURE_ADDRESS']; //楼层1的标题图片
              String floor2Title =
                  data['data']['floor2Pic']['PICTURE_ADDRESS']; //楼层1的标题图片
              String floor3Title =
                  data['data']['floor3Pic']['PICTURE_ADDRESS']; //楼层1的标题图片
              List<Map> floor1 =
                  (data['data']['floor1'] as List).cast(); //楼层1商品和图片
              List<Map> floor2 =
                  (data['data']['floor2'] as List).cast(); //楼层1商品和图片
              List<Map> floor3 =
                  (data['data']['floor3'] as List).cast(); //楼层1商品和图片
              String picture1 = data['data']['saoma']['PICTURE_ADDRESS'];
              String picture2 = data['data']['newUser']['PICTURE_ADDRESS'];
              String picture3 =
                  data['data']['integralMallPic']['PICTURE_ADDRESS'];
              return EasyRefresh(
                refreshHeader: ClassicsHeader(
                    key: _headerKey,
                    refreshText: '刷新中',
                    refreshedText: '刷新完成',
                    refreshingText: '',
                    bgColor: Colors.white,
                    textColor: Colors.pink,
                    moreInfoColor: Colors.pink,
                    showMore: true,
                    moreInfo: '',
                    refreshReadyText: '上拉刷新....'),
                refreshFooter: ClassicsFooter(
                    key: _footerKey,
                    bgColor: Colors.white,
                    textColor: Colors.pink,
                    moreInfoColor: Colors.pink,
                    showMore: true,
                    noMoreText: '',
                    loadingText: '加载中',
                    loadText: '加载中',
                    moreInfo: '加载中',
                    loadReadyText: '上拉加载....'),
                child: ListView(
                  children: <Widget>[
                    SwiperDiy(swiperDataList: swiperDataList), //页面顶部轮播组件
                    TopNavigator(navigatorList: navigatorDataList), //导航栏组建
                    AdBanner(adPicture: adPicture), //这是个广告图片 组建
                    LeadingPhone(
                        leaderPhone: leaderPhone,
                        leaderImage: leaderImage), //店长信息
                    Advvertisement(
                        pictureAddress1: picture1,
                        pictureAddress2: picture2,
                        pictureAddress3: picture3),
                    Recommend(recommandList: recommendList), //热销推荐
                    FloorTitle(picture_address: floor1Title),
                    FloorContent(floorGoodsList: floor1),
                    FloorTitle(picture_address: floor2Title),
                    FloorContent(floorGoodsList: floor2),
                    FloorTitle(picture_address: floor3Title),
                    FloorContent(floorGoodsList: floor3),
                    _hotGoods(),
                  ],
                ),
                onRefresh: () async {
                  print('开始下拉刷新');
                },
                loadMore: () async {
                  print('开始加载更多');
                  var formPage = {'page': page};
                  await request('homePageBelowConten', formData: formPage)
                      .then((val) {
                    var data = json.decode(val.toString());
                    List<Map> newGoodsList = (data['data'] as List).cast();
                    setState(() {
                      hotGoodsList.addAll(newGoodsList);
                      page++;
                    });
                  });
                },
              );
            } else {
              return Center(
                child: Text('加载中'),
              );
            }
          },
        ));
  }

  Widget hotTitle = Container(
      margin: EdgeInsets.only(top: 10.0),
      alignment: Alignment.center,
      color: Colors.transparent,
      padding: EdgeInsets.all(10.0),
      child: Text('火爆专区'));

  Widget _wrapList() {
    if (hotGoodsList.length != 0) {
      List<Widget> listWiget = hotGoodsList.map((val) {
        return InkWell(
          onTap: () {
            print('1');
           
          },
          child: Container(
            width: ScreenUtil().setWidth(372),
            color: Colors.white,
            padding: EdgeInsets.all(8.0),
            margin: EdgeInsets.only(bottom: 3.0),
            child: Column(
              children: <Widget>[
                InkWell(
                  onTap: () {
                     Application.router.navigateTo(context, "/detail?id=${val['goodsId']}");
                    print('点击了火爆专区的产品${val['image']}');
                  },
                  child: Image.network(val['image'],
                      width: ScreenUtil().setWidth(370)),
                ),
                Text(
                  val['name'],
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                      color: Colors.pink, fontSize: ScreenUtil().setSp(26)),
                ),
                Row(
                  children: <Widget>[
                    Text('￥${val['price']}'),
                    Text(
                      '￥${val['mallPrice']}',
                      style: TextStyle(
                          color: Colors.black26,
                          decoration: TextDecoration.lineThrough),
                    )
                  ],
                )
              ],
            ),
          ),
        );
      }).toList();
      return Wrap(
        spacing: 2, //2列
        children: listWiget,
      );
    } else {
      return Text('');
    }
  }

  Widget _hotGoods() {
    return Container(
      child: Column(
        children: <Widget>[hotTitle, _wrapList()],
      ),
    );
  }

  
}
